<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #profilePicture="{ model, field }">
        <Upload
          v-model:file-list="fileList"
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadApi"
          :before-upload="beforeUpload"
          :headers="token"
          @change="handleChange($event, { model, field })"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <loading-outlined v-if="loading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传产品图片</div>
          </div>
        </Upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { ref, computed, unref, defineComponent } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './customer.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { saveCustomer, updateCustomer, Api } from '/@/api/plm/customer/customer';
  import { getFields, getFormSchemas } from '/@/utils/permission/permission';
  import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Upload } from 'ant-design-vue';
  import { getToken } from '/@/utils/auth';
  import { saveProduct, updateProduct, uploadApi } from '/@/api/plm/product/product';

  export default defineComponent({
    name: 'CustomerModal',
    components: { PlusOutlined, Upload, LoadingOutlined, BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      // const emit = defineEmits(['success', 'register']);
      const record = ref();
      const isUpdate = ref(true);
      const { createMessage } = useMessage();
      getFormSchemas(formSchema, getFields(Api.GetCustomerByPage));
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        imageUrl.value = '';
        resetFields();
        setModalProps({ confirmLoading: false });
        record.value = data.record;
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });
      // const getTitle = computed(() => (!unref(isUpdate) ? '新增行业' : '编辑行业'));
      async function handleSubmit() {
        try {
          const values = await validate();
          // values.customerImg = imageUrl.value;
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            const data = await updateCustomer(values);
            if (data.code === 200) {
              createMessage.success(data.message);
            } else {
              createMessage.error(data.message);
            }
          } else {
            const data = await saveCustomer(values);
            if (data.code === 200) {
              createMessage.success(data.message);
            } else {
              createMessage.error(data.message);
            }
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      const loading = ref<boolean>(false);
      const token = {
        Authorization: getToken(),
      };
      const imageUrl = ref<string>('');
      const fileList = ref([]);
      const handleChange = (info: Recordable, { model, field }) => {
        const file = info.file;
        const status = file?.status;
        // const url = file?.response?.result.url;
        let url = file?.response?.result;
        if (status === 'uploading') {
          loading.value = true;
          return;
        }
        if (status === 'done') {
          console.log('产品图片地址：：', url);
          if (!url.startsWith('/')) {
            url = '/' + url;
          }
          imageUrl.value = 'http://localhost:8082/api' + url;
          // imageUrl.value = url;
          model[field] = url;
          loading.value = false;
        }
        if (status === 'error') {
          loading.value = false;
          createMessage.error('上传产品图片失败！');
        }
      };
      const beforeUpload = (file: File) => {
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
          createMessage.error('产品图片大小最大10MB!');
        }
        return isLt2M;
      };

      return {
        registerModal,
        registerForm,
        // getTitle,
        handleSubmit,
        fileList,
        handleChange,
        beforeUpload,
        token,
        imageUrl,
        uploadApi,
      };
    },
  });
</script>
